// --------------------USER--------------------------
var User = require('../models/user');
// ACTION
exports.signup = function (req, res) {
  var _user = req.body.user;

  User.findOne({
    name: _user.name
  }, function (err, user) {
    if (err) {
      console.log(err.code, err.message);
    }
    if (user) { // 用户名已经注册
      res.redirect('/signin');
    } else {
      user = new User(_user);
      user.save(function (err, user) {
        if (err) {
          console.log(err.code, err.message);
          return;
        }
        res.redirect('/');
      });
    }
  });
};
exports.signin = function (req, res) {
  var _user = req.body.user;
  var name = _user.name;
  var password = _user.password;

  User.findOne({
    name: name
  }, function (err, user) {
    if (err) {
      console.log(err.code, err.message);
    }
    if (!user) { // 数据库里查不到用户 - 登录失败 返回注册
      return res.redirect('/signup');
    }

    // 接着比对密码
    user.comparePassword(password, function (err, isMatch) {
      if (err) {
        console.log(err.code, err.message);
      }
      if (isMatch) { // 登录成功
        req.session.user = user; // session 保存登录状态
        console.log('user ' + user.name + ' signed in successfully');
        return res.redirect('/'); // FIXME
      } else { // 密码错误
        console.log('user ' + user.name + '\'s password did not match');
        return res.redirect('/signin');
      }
    });
  });
};
exports.logout = function (req, res) {
  delete req.session.user;
  // delete res.locals.user;
  res.redirect('/');
};
// PAGE
exports.showSignup = function (req, res) {
  res.render('signup', {
    title: '注册页面',
  });
};
exports.showSignin = function (req, res) {
  res.render('signin', {
    title: '登录页面',
  });
};
exports.list = function (req, res) {
  User.fetch(function (err, users) {
    if (err) {
      console.log(err);
    }
    res.render('userlist', {
      title: '列表页',
      users: users
    });
  });
};
// MIDWARE
exports.signinRequired = function (req, res, next) {
  var user = req.session.user;
  if (!user) return res.redirect('/signin');
  next(); // goto check user role
};

exports.adminRequired = function (req, res, next) {
  var user = req.session.user;
  if (user.role < 10) return res.redirect('/');
  next();
};

exports.superAdminRequired = function (req, res, next) {
  var user = req.session.user;
  if (user.role < 50) return res.redirect('/');
  next();
};
